package archimede;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Scanner;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JPanel;

import com.itextpdf.text.Document;

import net.miginfocom.swing.MigLayout;

public class ProfessionistaPanel extends JPanel {

	private JButton addIntermedi = new JButton("Aggiungi dati professionista o amministratore",
			new ImageIcon(ClassLoader.getSystemResource("plus.png")));
	private ArrayList<ProfessionistaObject> professionista = new ArrayList<ProfessionistaObject>();

	private int count = 0;
	private StartingWindow st;

	public ProfessionistaPanel(final StartingWindow st) {
		super();
		setOpaque(false);
		setLayout(new MigLayout());
		this.st = st;

		addIntermedi.setBorder(null);
		addIntermedi.setContentAreaFilled(false);
		addIntermedi.setRolloverEnabled(true);
		addIntermedi.setRolloverIcon(new ImageIcon(ClassLoader
				.getSystemResource("plus_roll.png")));

		addIntermedi.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				professionista.add(new ProfessionistaObject(count,
						ProfessionistaPanel.this));

				add(professionista.get(count), "cell 0 " + (++count));
				// count++;
				if (count < 15)
					add(addIntermedi, "cell 0 " + (1 + count));
				else
					remove(addIntermedi);
				paintAll(getGraphics());
				st.refresh();
			}
		});

		add(addIntermedi);
	}

	public void removeTabel(int line) {
		count--;
		// rilievi.remove(values[line]);

		remove(professionista.get(line));
		professionista.remove(line);
		for (int i = line; i < count; i++) {
			professionista.get(i).setCount(i);

			add(professionista.get(i), "cell 0 " + (i + 1));

		}

		if (count < 15)
			add(addIntermedi, "cell 0 " + (1 + count));
		else
			remove(addIntermedi);

		st.refresh();
	}

	public String print() {
		String print = "";
		print = "\n#" + count;
		for (int i = 0; i < count; i++) {
			print = print + "\n" + professionista.get(i).print();
		}
		return print;
	}

	public void setElement(String data) {
		// System.out.println("~~ " + data);
		Scanner c = new Scanner(data);
		try {
			count = Integer.parseInt(c.nextLine());
		} catch (Exception e) {
			count = 0;
		}
		// System.out.println("~~count " + count);
		for (int i = 0; i < count; i++) {
			String tmp = "";
			for (int j = 0; j < 10; j++) {
				try {
					tmp = tmp + c.nextLine() + "\n";
				} catch (Exception e) {
					tmp = tmp + "\n";
				}
			}
			professionista.add(new ProfessionistaObject(i,
					ProfessionistaPanel.this));
			add(professionista.get(i), "cell 0 " + (i + 1));
			if (count < 15)
				add(addIntermedi, "cell 0 " + (2 + i));
			else
				remove(addIntermedi);
			professionista.get(i).setElement(tmp);
		}
	}

	public int pdf(Document doc) {
		for (int i = 0; i < count; i++)
			professionista.get(i).pdf(doc);
		return count;
	}
}
